<template>
  <DialogBox
    :visible="boxVisibility"
    @update:visible="boxVisibility = $event"
    resize
    title="BOM配置"
    width="80%"
    :close-on-click-modal="false"
  >
    <Grid
      ref="gridRef"
      border
      :fetch-data="fetchData"
      max-height="500"
      :auto-load="false"
      :pager="pagerConfig"
      :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
      @edit-closed="editClosed"
    >
      <template #toolbar>
        <GridToolbar>
          <template #buttons>
            <div style="display: flex;">
              <Input v-model="spu" placeholder="款号" clearable />
              <Button type="primary" style="margin: 0 10px;" @click="search">查询</Button>
              <FileUpload
                ref="uploadRef1"
                :http-request="httpRequest"
                :file-list="fileList"
                accept=".xlsx"
                :show-file-list="false"
                style="margin-right: 10px;"
              >
                <template #trigger>
                  <tiny-button type="primary">上传物料BOM</tiny-button>
                </template>
              </FileUpload>
              <div v-if="upload_time" class="uploadTime">上传时间： {{ upload_time }}</div>
            </div>
          </template>
        </GridToolbar>
      </template>
      <GridColumn type="index" width="60"></GridColumn>
      <GridColumn field="identifier" title="识别码" min-width="180" ></GridColumn>
      <GridColumn field="store1" title="店铺" min-width="100" ></GridColumn>
      <GridColumn field="size" title="尺码" min-width="100" ></GridColumn>
      <GridColumn field="spu" title="款号" min-width="100" ></GridColumn>
      <GridColumn field="style" title="款式" min-width="180" ></GridColumn>
      <GridColumn field="garment_color" title="成衣颜色" min-width="100" ></GridColumn>
      <GridColumn field="materials_category_1" title="物料分类" min-width="100" ></GridColumn>
      <GridColumn field="materials_code" title="物料编号" min-width="100" ></GridColumn>
      <GridColumn field="materials_category_name" title="物料品类名称" width="180" ></GridColumn>
      <GridColumn field="materials_color" title="物料颜色" min-width="100" ></GridColumn>
      <GridColumn field="component" title="成份" min-width="100" ></GridColumn>
      <GridColumn field="order_quantity" title="订单数量（件）" min-width="100" ></GridColumn>
      <GridColumn field="dosage" title="用量" min-width="100" ></GridColumn>
      <GridColumn field="unit1" title="单位" min-width="100" ></GridColumn>
      <GridColumn field="loss" title="损耗" min-width="100" ></GridColumn>
      <GridColumn field="unit_conversion" title="单位转换" min-width="100" ></GridColumn>
      <GridColumn field="materials_need" title="物料需求数" min-width="180" ></GridColumn>
      <GridColumn field="unit2" title="单位" min-width="100" ></GridColumn>
      <GridColumn field="breadth" title="幅宽/规格" min-width="100" ></GridColumn>
      <GridColumn field="grams1" title="克重" min-width="100" ></GridColumn>
      <GridColumn field="materials_define" title="物料定义" min-width="100" ></GridColumn>
      <GridColumn field="store2" title="店铺" min-width="100" ></GridColumn>
      <GridColumn field="real_breadth" title="实用幅宽" min-width="100" ></GridColumn>
      <GridColumn field="grams2" title="克重" min-width="100" ></GridColumn>
      <GridColumn field="usage_bundling_strips" title="捆条用量" min-width="100" ></GridColumn>
      <GridColumn field="preload_for_bulk_cargo" title="大货预裁用量" min-width="100" ></GridColumn>
      <GridColumn field="discharge_utilization_rate" title="排料利用率（%）" min-width="100" ></GridColumn>
      <GridColumn field="number_cutting_beds" title="裁床数/1条布" min-width="100" ></GridColumn>
      <GridColumn field="materials_color_category" title="物料颜色分类" min-width="100" ></GridColumn>
      <GridColumn field="material_category_2" title="物料品类" min-width="100" ></GridColumn>
      <GridColumn field="fabric_cycle" title="面料周期" min-width="100" ></GridColumn>
      <GridColumn field="accessory_cycle" title="辅料周期" min-width="100" ></GridColumn>
      <GridColumn field="spu_definition" title="款式定义" min-width="100" show-icon></GridColumn>
    </Grid>
    <template #footer>
      <Button type="primary" @click="boxVisibility = false"> 关闭 </Button>
    </template>
  </DialogBox>
</template>

<script setup>
import { Button, DialogBox, Grid, GridColumn, GridToolbar, FileUpload, Input, Modal } from '@opentiny/vue'
import { uploadBomTemplate, getBomTemplate, updateBomTemplate } from '@/request/api'
import { ref, watch } from 'vue'
const boxVisibility = ref(false)
const pagerConfig = ref({
  attrs: {
    currentPage: 1,
    pageSize: 10,
    pageSizes: [10, 20, 30, 50, 100],
    total: 0,
    align: 'right',
    layout: 'total, prev, pager, next, jumper, sizes'
  }
})
let timer = null
const input = () => {
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    gridRef.value.clearActived()
  },3000)
}
const editor = ref({ component: 'input', autoselect: true,events: { input } })
const upload_time = ref('')
const spu = ref('')
const fileList = ref([])
const httpRequest = (files) => {
  const formData = new FormData()
  formData.append('file', files.file)
  uploadBomTemplate(formData,{'content-type': 'application/x-www-form-urlencoded'}).then(res => {
    if (res?.data?.ret === 0) {
      Modal.message({ message: '成功上传BOM配置文件', status: 'success' })
    } else {
      Modal.message({ message: res.data.msg, status: 'error' })
    }
  }).catch(() => {
    Modal.message({ message: '上传BOM配置文件失败', status: 'error' })
  })
}
const gridRef = ref()
const search = () => {
  gridRef.value.fetchData.args = {
    spu: spu.value
  }
  gridRef.value.handleFetch()
}
const getData = ({ page, spu }) => {
  const currentPage = page.currentPage
  const size = page.pageSize
  const keyWords = spu || ''
  return new Promise((resolve) => {
    getBomTemplate(keyWords, currentPage, size).then(res => {
      if (res?.data?.ret === 0) {
        upload_time.value = res.data.upload_time
        resolve({
          result: res.data.result,
          page: { total: res.data.total }
        })
      }
    })
  })
}
const fetchData = {
  api: getData
}
const editClosed = ({ column, row }) => {
  const field  = column.property
  const title = column.title
  const hasChange = gridRef.value.hasRowChange(row, field)
  if (hasChange) {
    const params = {
      id: row.id,
      edit_field: field,
      edit_value: row[field]
    }
    updateBomTemplate(params).then(res => {
      if (res?.data?.ret !== 0) {
        Modal.message({ message: `编辑${title}失败 `, status: 'error' })
      }
    })
  }
}
defineExpose({
  boxVisibility
})
watch(boxVisibility, (val) => {
  if (val) {
    gridRef.value.handleFetch()
  }
})
</script>

<style lang="scss" scoped>
  .uploadTime {
    position: absolute;
    right: 0;
    line-height: 60px;
    color: red;
    font-size: 16px;
  }
</style>